瀏覽器自動化(4) Selenium + Beautiful Soup

安裝模塊

1
2
3
selenium
requests
beautifulsoup4
  1. selenium
    主要用於登入或js互動,剩餘的在使用bs4進行爬取。
  1. requests
    能模擬http請求,如:get、post、put、delete,通常是爬取分頁或a標籤時用到。

官方文檔

如何使用

模擬請求

1
r = requests.get('https://api.github.com/events')

查看請求狀態

1
2
3
r.status_code
輸出:
>>> 200

取得請求html內容

1
2
3
r.text
輸出:
>>> '<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="zh-TW"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" ...</html>'
  1. Beautiful Soup
    Beautiful Soup能解析html,能快速尋找標籤內容,也可以透過CSS選擇器快速尋找帶有標籤屬性的內容。

官方文檔

如何使用

1
2
3
4
5
from bs4 import BeautifulSoup
import requests
web_data = requests.get('https://api.github.com/events')
soup = BeautifulSoup(web_data, 'lxml') #解析Html
soup.title

啟動

基本使用

selenium_bs4_demo1.py

1
2
3
4
5
6
7
8
from bs4 import BeautifulSoup

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://w3.iiiedu.org.tw/')
wb_html = browser.page_source
soup = BeautifulSoup(wb_html,"lxml")

小結

大部分網頁都用requests都能獲取,用到selenium情況比較少,有登入或js需求可以參考,在此紀錄心得。